package handler

import (
	"exam/api/request"
	"exam/internal/dao"
	"exam/internal/model"
	"github.com/gin-gonic/gin"
	"net/http"
)

func ExamList(c *gin.Context) {
	var data []*model.Exam
	list, b := dao.ExamList(data)
	if b == false {
		c.JSON(http.StatusOK, gin.H{
			"code":    http.StatusOK,
			"message": "考试信息列表失败",
			"data":    list,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "考试信息列表成功",
		"data":    list,
	})

}

func ExamSub(c *gin.Context) {
	var req request.AddExamNum
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    10000,
			"message": "获取参数失败",
			"data":    err.Error(),
		})
		return
	}

	var data model.Exam
	dao.GetOneById(req.ExamId, &data)
	if data.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code":    10000,
			"message": "该场考试不存在",
			"data":    nil,
		})
		return
	}

	exam := model.ExamNum{
		UserId:     c.GetUint("userId"),
		ExamId:     req.ExamId,
		ExamNumber: req.ExamNumber,
	}
	if !dao.Create(&exam) {
		c.JSON(http.StatusOK, gin.H{
			"code":    10000,
			"message": "新考试创建失败",
			"data":    nil,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "提交考试成功",
		"data":    exam,
	})
}

func History(c *gin.Context) {

	var data []model.ExamNum

	if !dao.GetListByFields(&model.ExamNum{UserId: c.GetUint("userId")}, &data) {
		c.JSON(http.StatusOK, gin.H{
			"code":    10000,
			"message": "考试历史记录查询失败",
			"data":    nil,
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "考试历史记录查询成功",
		"data":    data,
	})

}
